package com.shamine.kuaiqiao.blink.detail.play

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.BmobUser
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.shamine.kuaiqiao.blink.R
import com.shamine.kuaiqiao.blink.basic.BaseActivity
import com.shamine.kuaiqiao.blink.basic.GlideApp
import com.shamine.kuaiqiao.blink.data.Gallery
import com.shamine.kuaiqiao.blink.data.Passer
import com.shamine.kuaiqiao.blink.data.Photo
import com.shamine.kuaiqiao.blink.events.EventGallery
import com.shamine.kuaiqiao.blink.events.EventSignOut
import kotlinx.android.synthetic.main.activity_play.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import rx.Subscriber
import kotlin.concurrent.thread

class Play : BaseActivity(),View.OnClickListener {

    private lateinit var gallery: Gallery
    private var step = 0
    private lateinit var urls:MutableMap<Int,String>
    private lateinit var dates: MutableMap<Int,String>
    private var number = 0

    override fun onSignOut(event: EventSignOut) {
        EventBus.getDefault().unregister(this)
        finish()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_play)
        EventBus.getDefault().register(this)
        if (isConnected())
            GlideApp.with(this).load(gallery.cover?.fileUrl).into(cover)
        else status.text = getString(R.string.status_device_offline)

    }

    override fun onClick(p0: View?) {
        when(p0?.id){
            R.id.play -> {
                when(step){
                    0 -> {
                        urls = mutableMapOf()
                        dates = mutableMapOf()
                        step = 1 //preparing
                        play.visibility = View.GONE
                        status.text = getString(R.string.status_preparing)
                        prepare()
                    }
                    2,4 -> {
                        step = 2
                        status.visibility = View.GONE
                        play.visibility = View.GONE
                        play()
                    }
                }
            }
        }
    }

    private fun play(){
        println("step==$step")
        thread {
            var index = urls.size
            while (step == 2) {
                if (isFinishing || isDestroyed) break else
                runOnUiThread {
                        GlideApp.with(this)
                                .asDrawable()
                                .centerCrop()
                                .load(urls[index])
                                .onlyRetrieveFromCache(true)
                                .dontAnimate()
                                .dontTransform()
                                .skipMemoryCache(true)
                                .into(object : SimpleTarget<Drawable>(450, 800) {
                                    override fun onResourceReady(drawable: Drawable?, transition: Transition<in Drawable>?) {
                                        cover.setImageDrawable(drawable)
                                    }
                                })
                        date.text = dates[index]
                }
                index -= 1
                if (index <= 0) {
                    step = 4 //play finished
                    runOnUiThread {
                        play.visibility = View.VISIBLE
                        status.text = getString(R.string.status_play_finished)
                    }
                    break
                }
                Thread.sleep(300)
            }
        }
    }

    private fun prepare(){
        val query = BmobQuery<Photo>()
        query.addWhereEqualTo("passer", BmobUser.getCurrentUser(Passer::class.java))
        query.addWhereEqualTo("gallery",gallery)
        query.setLimit(100)
        query.order("-createdAt")
        query.findObjectsObservable(Photo::class.java).subscribe(object: Subscriber<MutableList<Photo>>(){
            override fun onNext(list: MutableList<Photo>?) {
                var index = 0
                while (true){
                    download(list!![index],index)
                    index++
                    if (index >= list.count()) break
                }
            }

            override fun onError(p0: Throwable?) {
                toast(this@Play,"onError: ${p0?.message}")
            }

            override fun onCompleted() {
            }
        })
    }

    private fun download(photo: Photo,index: Int) {
        GlideApp.with(this)
                .asDrawable()
                .load(photo.photo.fileUrl)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .listener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                        toast(this@Play,e!!.message.toString())
                        return false
                    }

                    override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                        number += 1
                        val size = if (gallery.size<100) gallery.size else 100
                        status.text = getString(R.string.status_preparing).plus(number).plus("/$size")
                        urls.put(index,photo.photo.fileUrl)
                        dates.put(index,photo.createdAt.substring(0,10))
                        if (number >= size){
                            status.text = getString(R.string.status_prepare_done)
                            play.visibility = View.VISIBLE
                            step = 2 //prepare done
                        }
                        return true
                    }
                }).preload(450,800)
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        Glide.get(this).clearMemory()
        Thread{
            Glide.get(this).clearDiskCache()
        }.start()
        super.onDestroy()
    }
    /**
     * 获取点击的相册
     */
    @Subscribe(sticky = true)
    fun galleryReceiver(event: EventGallery){
        if (event.cls == javaClass) {
            this.gallery = event.gallery
        }
    }
}
